package com.heima.freemarker;

import com.alibaba.fastjson.JSONArray;

import com.heima.file.MinIoTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.*;

@Component
public class FreemarkerTemplate {
	
	@Autowired
	private Configuration configuration;
	
	@Autowired
	private MinIoTemplate minIoTemplate;
	
	/**
	 * 生成静态文件
	 *
	 * @param content 文件内容
	 * @return 文件流
	 * @throws IOException       IOException
	 * @throws TemplateException TemplateException
	 */
	public InputStream generate(String content) throws IOException, TemplateException {
		Template template = configuration.getTemplate("article.ftl");
		
		Map<String, Object> params = new HashMap<>();
		params.put("content", JSONArray.parseArray(content));
		
		// 也可以以流的形式输出
		StringWriter out = new StringWriter();
		template.process(params, out);
		return new ByteArrayInputStream(out.toString().getBytes());
	}
	
	/**
	 * 生成静态文件并上传到MinIO
	 *
	 * @param content  文件内容
	 * @param fileName 文件名
	 * @return 文件远程地址
	 * @throws IOException       IOException
	 * @throws TemplateException TemplateException
	 */
	public String generateAndUpload(String content, String fileName) throws IOException, TemplateException {
		InputStream generate = generate(content);
		return minIoTemplate.uploadFile("", fileName, generate, "html");
	}
}
